package org.jeefb.common.utils;
import java.io.BufferedWriter;
 import java.io.File;
 import java.io.FileWriter;
 import java.io.Writer;
 import java.util.Properties;
 import java.util.UUID;
 import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 import org.springframework.core.io.ClassPathResource;
 import org.springframework.core.io.FileSystemResource;
 import org.springframework.core.io.Resource;
 import org.springframework.core.io.support.PropertiesLoaderUtils;
 
 public class NodeUtils
 {
   private static final Logger logger = LoggerFactory.getLogger(NodeUtils.class);
  
   public static String getUUID32()
   {
     return UUID.randomUUID().toString().replaceAll("-", "");
   }
   
   private static String clientId = "";
   
   public static String readNodeId()
  {
     try
     {
      if (StringUtils.isBlank(clientId))
       {
        String clientIdPath = "";
         
         Resource r = new ClassPathResource("node.properties");
        if (r.exists())
        {
           Properties nodeProperties = PropertiesLoaderUtils.loadProperties(r);
           clientIdPath = nodeProperties.getProperty("clientId.filePath");
          if (StringUtils.isBlank(clientIdPath)) {
             clientIdPath = "clientId.properties";
           }
        }
        else
         {
          clientIdPath = "clientId.properties";
         }
         Resource clientIdResource = new FileSystemResource(clientIdPath);
        if (clientIdResource.exists())
        {
          Properties clentProperties = PropertiesLoaderUtils.loadProperties(clientIdResource);
           clientId = clentProperties.getProperty("id");
           if (StringUtils.isBlank(clientId))
           {
             clientId = getUUID32();
             Writer output = new BufferedWriter(new FileWriter(new File(clientIdPath)));
             clentProperties.setProperty("id", clientId);
            clentProperties.store(output, "client id");
             output.close();
          }
        }
         else
         {
          Properties clentProperties = new Properties();
           clientId = getUUID32();
          Writer output = new BufferedWriter(new FileWriter(new File(clientIdPath)));
          clentProperties.setProperty("id", clientId);
          clentProperties.store(output, "client id");
          output.close();
         }
      }
     }
     catch (Exception e)
    {
      logger.error("*", e);
     }
   return clientId;
   }
 }